/*
* Copyright(C) 2009, kesalin All rights reserved.
* 
* File name : TSFHack.h
* Brief     : TSFHack.
* Version   : 1.0
* Author    : kesalin@gmail.com
* Date      : 2009-6-5
*/

#pragma once

#include <msctf.h>

namespace LuoUtils {

// TSFManager
class TSFManager {

	ITfThreadMgr* m_pManger;

	TfClientId m_cid;

public:

	TSFManager() : m_pManger(0), m_cid(0)
	{
	}

	~TSFManager()
	{
		SafeRelease();
	}

	void SafeRelease()
	{
		if (m_pManger != 0) {
			m_pManger->Release();
			m_pManger = 0;
		}
	}

	void Release()
	{
		if (m_pManger != 0) {
			HRESULT hRslt = m_pManger->Deactivate();
			if (FAILED(hRslt)) {
				ATLTRACE("TSFManager::Release() ITfThreadMgr::Deactivate ERR: %08X\n", hRslt);
			}

			SafeRelease();
		}
	}

	void Activate()
	{
		if (m_pManger != 0) {
			return;
		}

		void* ppv = 0;
		HRESULT hRslt = CoCreateInstance(
			CLSID_TF_ThreadMgr,
			0,
			CLSCTX_INPROC_SERVER,
			IID_ITfThreadMgr,
			&ppv);
		if (FAILED(hRslt)) {
			ATLTRACE("TSFManager::Activate() CoCreateInstance WARN: %08X\n", hRslt);
			return;
		}

		m_pManger = static_cast<ITfThreadMgr*>(ppv);

		hRslt = m_pManger->Activate(&m_cid);
		if (FAILED(hRslt)) {
			ATLTRACE("TSFManager::Activate() ITfThreadMgr::Activate ERR: %08X\n", hRslt);
			SafeRelease();
			return;
		}
	}

}; // TSFManager

} // namespace LuoUtils

